/*
 * @Descripttion: webSocket
 * @Define: 实例化一个webSocket对象，连接多个url
 * @Use: var ws1 = new InitWebSocket(`ws://url1`);
 * @Use: ws1.onopen = function () { const msg = {}; this.websocket.send(JSON.stringify(msg)) };
 * @Use: ws1.onmessage = function (e) { const data = e.data };
 * @Author: yeming
 * @Date: 2019-07-01 17:59:45
 */

// import {
//   heartBeat
// } from './heartBeat.js';

/** webSocket 请求封装 */

function InitWebSocket(wsuri) {
  this.wsuri = wsuri; // webSocket的请求地址
  this.lockReconnect = true; // 避免重连的机制
  // this.HeartCheck = heartBeat;

  this.try = null; // 尝试重连
  this.count = 0; // 重连次数
  this.maxCount = 10; // 最大重连次数
  this.heartBeatClock = null; // 心跳连接的setTimeout函数
  var _this = this;

  this.initWebSocket = function () { // 重启一个新的webSockt
    _this.websocket = new WebSocket(_this.wsuri);
    _this.websocket.onmessage = function (e) {
      const redata = e.data;
      // 一旦收到数据不管是甚么数据，说明活着
      // this.HeartCheck.start(this.websocket)
      // if (parseInt(redata.data.type, 10) === 95001) {
      //   _this.HeartCheck.reset(_this.websocket); // 发送心跳信息
      // }
      _this.onmessage(redata); // 调用用户自定义的数据处理方式
    };
    _this.websocket.onclose = function () {
      console.log('WebSocket 连接关闭');
      _this.websocket.close();
      clearTimeout(_this.try);
      _this.try = setTimeout(() => {
        _this.reconnectWebSocket();
      }, 5000);
    };
    _this.websocket.onopen = function () {
      console.log('WebSocket 连接成功');
      // _this.HeartCheck.start(_this.websocket);
      _this.onopen();
    };
    // 连接发生错误的回调方法
    _this.websocket.onerror = function () {
      console.log('WebSocket 连接发生错误');
      clearTimeout(_this.try);
      _this.try = setTimeout(() => {
        _this.reconnectWebSocket();
      }, 5000);
    };
  };
  this.reconnectWebSocket = function () {
    this.count++;
    if (_this.lockReconnect || this.count >= this.maxCount) {
      _this.websocket.close();
      return false;
    };
    _this.lockReconnect = true;
    // 没连接上会一直重连，设置延迟避免请求过多
    _this.heartBeatClock && clearTimeout(this.heartBeatClock);
    _this.heartBeatClock = setTimeout(() => {
      _this.initWebSocket();
      _this.lockReconnect = false;
      console.log('connect again');
    }, 5000);
  };
  this.initWebSocket();
  return this;
};

InitWebSocket.prototype.onopen = function () {};
InitWebSocket.prototype.onmessage = function () {}; // 便于外部重新定义方法处理数据
InitWebSocket.prototype.onclose = function () {
  this.websocket.close();
};
InitWebSocket.prototype.send = function (data) {
  if (this.websocket.readyState === 1) {
    this.websocket.send(data);
  } else {
    console.log("webSocket 未正常连接");
  }
};

export default InitWebSocket;
